package com.example.zwgt.yrfk.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.Toast;

import com.example.zwgt.yrfk.App;
import com.example.zwgt.yrfk.bean.PublicConfigResponseInfo;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by xiaochen on 2017/2/22.
 * 获取一些常用信息的工具类
 *
 * @email xiaochenu@gmail.com
 */

public class Util {
    static TelephonyManager telephonyManager;
    static Context context;
    public static final int REQUEST_SUCCESS = 1;
    public static final int REQUEST_FAIL = -1;
    public static Toast toast;

    public static void makeToast(String data) {
        if (toast == null) {
            toast = Toast.makeText(context, data, Toast.LENGTH_SHORT);
        } else {
            toast.setText(data);
        }
        toast.show();
    }

    /**
     * 公共配置
     */
    public static PublicConfigResponseInfo publicConfigResponseInfo;

    static {
        context = App.context;
        telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    }

    private Util() {
    }

    /**
     * 获取X-Device-IdtelephonyManager.getSubscriberId()
     */
    public static String getIMSI() {
        TelephonyManager TelephonyMgr = (TelephonyManager)App.context.getSystemService(Context.TELEPHONY_SERVICE);
        String szImei = TelephonyMgr.getDeviceId();
        return szImei;
    }

    /**
     * 获取X-Platform
     *
     * @return Android 6.0
     */
    public static String getPlatform() {
        return "Android " + android.os.Build.VERSION.RELEASE + "";
    }

    /**
     * 获取X-Version
     */
    public static String getVersion() {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取x-platform-type
     */
    public static String getPlatFormType() {
        return android.os.Build.MODEL;
    }

    //获取时间
    public String getDate() {
        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT
        String str = sdf.format(cd.getTime());
        return str;
    }

    /**
     * 对字符串进行MD5加密
     */
    public static String getMD5(String val) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(val.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * 获取需加密的元数据
     * md5 96e79218965eb72c92a549dd5a330112
     * xuerid 178
     * post
     */
    public static String getSignature(String HttpMethod, String RequestUrl, String xUserId, String xDeviceId, String xVersion) {
        String signature = HttpMethod + "\n" + RequestUrl + "\n" + xUserId + "\n" + xDeviceId + "\n" + xVersion + "\n";
        return signature;
    }

    /**
     * 6.0请求权限 返回code为123 改程序主要为读取手机信息的权限
     *
     * @return
     */
    public static void requestReadPhoneStatePermission(Activity activity) {
        //检查权限是否获取
        if (ContextCompat.checkSelfPermission(activity,
                Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_PHONE_STATE},
                    123);
        }
    }

    /**
     * 转换时间 yy.MM.dd xx
     */
    public static String msToString(String ms) {
        if (!TextUtils.isEmpty(ms)) {
            Long i;
            if (ms.length() <= 10){
                i = Long.valueOf(ms) * 1000;//此处不*1000变得很小
            }else{
                i = Long.valueOf(ms);
            }
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM.dd");
            String time = sDateFormat.format(new Date(i));
            return time;
        } else {
            return "";
        }
    }

    /**
     * 20170101000000-->2017-01-01
     */
    public static String stringToTime(String data) {
        if (data.length() > 8){
            String times = data.substring(0, 4) + "-" + data.substring(4, 6) + "-" + data.substring(6, 8);
            return times;
        }
        return data;
    }

    /**
     * 获取审批状态
     */
    public static String getStatue(String progress) {
        Integer p = Integer.valueOf(progress);
        String result = "";
        switch (p) {
            case 1:
                result = "财富经理处理";
                break;
            case 3:
                result = "团队长审核";
                break;
            case 5:
                result = "录入客户资料";
                break;
            case 8:
                result = "录入完成";
                break;
            case 10:
                result = "风控审批中";
                break;
            case 20:
                result = "申请提高额度";
                break;
            case 40:
                result = "申请重新审批";
                break;
            case 50:
                result = "风控经理审批";
                break;
            case 60:
                result = "申请审批";
                break;
            case 100:
                result = "审批完成";
                break;
            case 200:
                result = "审批不通过";
                break;
            case 300:
                result = "终审不通过";
                break;
        }
        return result;
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    public static int getStatusBarHeight() {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 适配转换
     */
    public static int dip2px(float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private static final String HMAC_SHA1 = "HmacSHA1";

    /**
     * 生成签名数据
     * HMAC_SHA1 加密
     * @param data 待加密的数据
     * @param key  加密使用的key
     * @throws
     * @throws NoSuchAlgorithmException
     */
    public static String getSignature2(String data, String key) throws Exception {
        byte[] keyBytes=key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, HMAC_SHA1);
        Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        StringBuilder sb=new StringBuilder();
        for(byte b:rawHmac){
            sb.append(byteToHexString(b));
        }
        return sb.toString();
    }

    private static String byteToHexString(byte ib){
        char[] Digit={
                '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'
        };
        char[] ob=new char[2];
        ob[0]=Digit[(ib>>>4)& 0X0f];
        ob[1]=Digit[ib & 0X0F];
        String s=new String(ob);
        return s;
    }

    public static String getBase64(String str) {
        String result = "";
        if( str != null) {
            try {
                result = new String(Base64.encode(str.getBytes("utf-8"), Base64.NO_WRAP),"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获得加密请求头author的参数
     */
    public static String getXAuthor (String data, String key){
        try {
            String hmac_sha1_string = getSignature2(data, key);
            String base64 = getBase64(hmac_sha1_string);
            return base64;
        } catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
    }

    /**
     * 将otherImages里面的图片进行切割显示
     * @param otherImages
     * @return
     */
    public static String[] getOtherImageUrl(String otherImages){
        String[] otherImageUrl = otherImages.split(",");
        return otherImageUrl;
    }

    //............................................................................................获取设备唯一id的方式
    protected static final String PREFS_FILE = "gank_device_id.xml";
    protected static final String PREFS_DEVICE_ID = "gank_device_id";
    protected static String uuid;
    /**
     * 获取唯一标识码
     * @param mContext
     * @return
     */
    public synchronized static String getUDID(Context mContext)
    {
        if( uuid ==null ) {
            if( uuid == null) {
                final SharedPreferences prefs = mContext.getApplicationContext().getSharedPreferences( PREFS_FILE, Context.MODE_PRIVATE);
                final String id = prefs.getString(PREFS_DEVICE_ID, null );

                if (id != null) {
                    // Use the ids previously computed and stored in the prefs file
                    uuid = id;
                } else {

                    final String androidId = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
                    // Use the Android ID unless it's broken, in which case fallback on deviceId,
                    // unless it's not available, then fallback on a random number which we store
                    // to a prefs file
                    try {
                        if (!"9774d56d682e549c".equals(androidId)) {
                            uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")).toString();
                        } else {
                            final String deviceId = ((TelephonyManager) mContext.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
                            uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")).toString() : UUID.randomUUID().toString();
                        }
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }

                    // Write the value out to the prefs file
                    prefs.edit().putString(PREFS_DEVICE_ID, uuid).commit();
                }
            }
        }
        return uuid;
    }

    /**
     * 获得指定日期的前一天
     *
     * @param specifiedDay
     * @return
     * @throws Exception
     */
    public static String getSpecifiedDayBefore(String specifiedDay) {//可以用new Date().toLocalString()传递参数
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyyMMddHHmmss").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - 1);

        String dayBefore = new SimpleDateFormat("yyyyMMddHHmmss").format(c
                .getTime());
        return dayBefore;
    }

    /**
     * ms转换成时间具体到秒
     * @param millisecond
     * @return
     */
    public static String getDateTimeFromMillisecond(String millisecond){
        if (!TextUtils.isEmpty(millisecond)) {
            Long i;
            if (millisecond.length() <= 10){
                i = Long.valueOf(millisecond) * 1000;//此处不*1000变得很小
            }else{
                i = Long.valueOf(millisecond);
            }
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sDateFormat.format(new Date(i));
            return time;
        } else {
            return "";
        }
    }
}
